import text_processing
import tts_http_demo
import os
import json
from config import *
from tts_http_demo import merge_mp3_files
from merge_audio import merge_audio_with_order_and_overlap

# 处理单个小说文本
def deal_file(file_path, write_path):
    """
    将小说文本转为json文件
    """
    with open(file_path,'r',encoding='utf-8') as file:
        file_content = file.read()
    json_data = text_processing.chat_completions(file_content, text_processing.voice_list)
    text_processing.output_file(json_data, write_path)
    print("单个文本转换已经完成")

# 处理多个小说文本，不建议使用这个，一次处理太多内容可能很难得到希望的结果。
def deal_files(file_path):
    """
    将文件夹中的所有文件转为json文件，写入指定文件夹中
    """
    text_processing.transform_to_json(file_path)
    print("文本转换已经完成")

# 将json文本生成音频
def get_radio(json_path, file_name):
    """
    首先会生成一个个单独的音频，之后根据生成的单独音频整合在一起，得到最终结果
    最终结果放在merged_mp3文件夹中
    """
    #获取当前的工作目录
    root_dir = os.getcwd()

    #获取输入的剧本
    input_juben = os.path.join(root_dir, json_path)

    #中间结果和最终结果的存储位置
    path1 = os.path.join(root_dir, 'mp3_file')
    path2 = os.path.join(root_dir, 'merged_mp3')
    merge_name = file_name + '.mp3'
    mp3_dir = os.path.join(path1, file_name)
    merged_mp3 = os.path.join(path2, merge_name)


    if not os.path.exists(mp3_dir):
        os.makedirs(mp3_dir, exist_ok=True)

    with open(input_juben, encoding='utf-8') as reader:
        juben = json.load(reader)

    for key, value in juben.items():
        if value["type"] == "人声":
            tts_http_demo.get_voice(os.path.join(mp3_dir, key), value["info"]["voice_type"], value["info"]["content"])
        if value["type"] == "环境声":
            tts_http_demo.get_env_sound(os.path.join(mp3_dir, key), value["info"])

    #合并成一个音频
    output_order_path = os.path.join(root_dir, 'merged_json',f"{file_name}.json")
    merge_audio_with_order_and_overlap(json_path,mp3_dir, merged_mp3,output_order_path)
    print("音频生成完成")

if __name__ == '__main__':
    # test.deal_files('./origin_text', './new_text')
    # deal_file('./new_text/祝福_节选.txt', './output/祝福_节选.json')
    get_radio('./output/祝福_节选.json', '祝福_节选')